package com.tanhua.api.mongo;

import com.tanhua.mongo.Friend;
import com.tanhua.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Long userId, Long friendId) {
        Friend friend1 = new Friend();
        friend1.setCreated(System.currentTimeMillis());
        friend1.setUserId(userId);
        friend1.setFriendId(friendId.longValue());
        mongoTemplate.insert(friend1);


        Friend friend2 = new Friend();
        friend2.setCreated(friend1.getCreated());
        friend2.setUserId(friendId.longValue());
        friend2.setFriendId(userId);
        mongoTemplate.insert(friend2);
    }

    @Override
    public PageBeanVo contactsListByUserId(Integer page, Integer pagesize, Long id) {
        Query query = new Query(Criteria.where("userId").is(id));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        PageBeanVo pageBeanVo = new PageBeanVo(page, pagesize, count, friendList);
        return pageBeanVo;
    }

    @Override
    public Integer count(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Friend.class);
        return Math.toIntExact(count);
    }

    @Override
    public Boolean isFriend(Long userId, Long friendId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        long count = mongoTemplate.count(query, Friend.class);
        return count==0?false:true;
    }

    @Override
    public void removeFriend(Long userId, Long loveId) {
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(loveId));
        mongoTemplate.remove(query1,Friend.class);


        Query query2 = new Query(Criteria.where("userId").is(loveId).and("friendId").is(userId));
        mongoTemplate.remove(query2,Friend.class);
    }
}
